// lib/pages/music_page.dart
//
// 高级版音乐控制界面（纯 UI，暂不含 BLE 控制）
// --------------------------------------------------
// 集成说明：
// 1. 路由：GetPage(name: '/music', page: () => const MusicPage())
// 2. 首页按钮：onTap: () => Get.toNamed('/music')
// 3. 底部导航：依赖 CommonBottomNav（你已有）

import 'dart:math';
import 'dart:ui' show lerpDouble;

import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../widgets/common_bottom_nav.dart';

class MusicPage extends StatefulWidget {
  const MusicPage({Key? key}) : super(key: key);

  @override
  State<MusicPage> createState() => _MusicPageState();
}

class _MusicPageState extends State<MusicPage>
    with TickerProviderStateMixin {
  // 当前主题
  int currentTheme = 0;

  // 音量 0~1
  double volume = 0.5;

  // 播放状态
  bool isPlaying = false;

  // 大封面旋转动画
  late AnimationController _coverCtrl;

  // 旋钮轻微呼吸动画
  late AnimationController _glowCtrl;

  final PageController _themePageCtrl =
  PageController(viewportFraction: 0.32);

  @override
  void initState() {
    super.initState();

    _coverCtrl = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 20),
    ); // ❌ 不要 .repeat()，由播放按钮控制

    _glowCtrl = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 2),
      lowerBound: 0.0,
      upperBound: 1.0,
    )..repeat(reverse: true);
  }

  @override
  void dispose() {
    _coverCtrl.dispose();
    _glowCtrl.dispose();
    _themePageCtrl.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFF000000),
      body: Column(
        children: [
          _buildHeader(),
          Expanded(
            child: SingleChildScrollView(
              padding:
              const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
              child: Column(
                children: [
                  const SizedBox(height: 4),
                  _buildRotatingCover(),
                  const SizedBox(height: 14),
                  Text(
                    musicThemes[currentTheme].title,
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 20,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  const SizedBox(height: 28),
                  _buildVolumeSlider(),
                  const SizedBox(height: 30),
                  _buildVolumeKnob(),
                  const SizedBox(height: 30),
                  _buildPlayControls(),
                  const SizedBox(height: 20),
                ],
              ),
            ),
          ),
        ],
      ),
      bottomNavigationBar: const CommonBottomNav(),
    );
  }

  // 顶部栏：标题 + 蓝牙状态
  Widget _buildHeader() {
    return SafeArea(
      bottom: false,
      child: Container(
        padding:
        const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            const Text(
              "音乐",
              style: TextStyle(
                color: Colors.white,
                fontSize: 26,
                fontWeight: FontWeight.w700,
              ),
            ),
            GestureDetector(
              onTap: () {
                // TODO: 跳到你已有的设置页面
                // Get.toNamed('/settings');
              },
              child: Container(
                padding: const EdgeInsets.symmetric(
                    horizontal: 10, vertical: 4),
                decoration: BoxDecoration(
                  color: const Color(0xFF1976D2),
                  borderRadius: BorderRadius.circular(14),
                ),
                child: Row(
                  children: const [
                    Icon(Icons.bluetooth,
                        color: Colors.white, size: 16),
                    SizedBox(width: 4),
                    Text(
                      "已连接",
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 12,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 大封面旋转图（点击切换主题）
  Widget _buildRotatingCover() {
    final theme = musicThemes[currentTheme];

    return GestureDetector(
      onTap: () {
        // 停止播放时切换主题更合理，你可以加判断：
        // if (!isPlaying) { ... }
        setState(() {
          currentTheme = (currentTheme + 1) % musicThemes.length;
        });
      },
      child: RotationTransition(
        turns: _coverCtrl,
        child: Container(
          width: 240,
          height: 240,
          decoration: const BoxDecoration(
            shape: BoxShape.circle,
            gradient: RadialGradient(
              colors: [
                Color(0x11FFFFFF),
                Color(0xFF111111),
              ],
            ),
            boxShadow: [
              BoxShadow(
                color: Colors.black54,
                blurRadius: 26,
                offset: Offset(0, 18),
              ),
            ],
          ),
          alignment: Alignment.center,

          // 内部白色边框 + 图片
          child: Container(
            width: 210,
            height: 210,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              border: Border.all(
                color: Colors.white12,
                width: 2,
              ),
            ),
            clipBehavior: Clip.antiAlias,
            child: Image.asset(
              theme.image,
              fit: BoxFit.cover,
            ),
          ),
        ),
      ),
    );
  }

  // 上方线性音量条
  Widget _buildVolumeSlider() {
    return Row(
      children: [
        const Icon(Icons.volume_down,
            color: Colors.white70, size: 20),
        Expanded(
          child: SliderTheme(
            data: SliderTheme.of(context).copyWith(
              trackHeight: 4,
              thumbShape:
              const RoundSliderThumbShape(enabledThumbRadius: 9),
              overlayShape: SliderComponentShape.noOverlay,
              activeTrackColor: const Color(0xFF1E88E5),
              inactiveTrackColor: Colors.white10,
              thumbColor: const Color(0xFF1E88E5),
            ),
            child: Slider(
              value: volume,
              onChanged: (v) => setState(() => volume = v),
            ),
          ),
        ),
      ],
    );
  }

  // 中间旋钮音量
  Widget _buildVolumeKnob() {
    return SizedBox(
      width: 220,
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onPanUpdate: (details) {
          // 简单根据左右滑动调节音量
          setState(() {
            volume = (volume + details.delta.dx * 0.005)
                .clamp(0.0, 1.0);
          });
        },
        child: Column(
          children: [
            AnimatedBuilder(
              animation: _glowCtrl,
              builder: (_, __) {
                return CustomPaint(
                  size: const Size(190, 190),
                  painter: _KnobPainter(
                    volume: volume,
                    glow: _glowCtrl.value,
                    isPlaying: isPlaying,
                  ),
                );
              },
            ),
            const SizedBox(height: 6),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: const [
                Text("Min",
                    style: TextStyle(color: Colors.white70)),
                Text("VOL",
                    style: TextStyle(color: Colors.white70)),
                Text("Max",
                    style: TextStyle(color: Colors.white70)),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // 下方播放控制按钮
  Widget _buildPlayControls() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        IconButton(
          icon: const Icon(Icons.skip_previous, color: Colors.white),
          iconSize: 40,
          onPressed: () {
            // TODO: 上一曲
          },
        ),
        IconButton(
          icon: Icon(
            isPlaying ? Icons.pause_circle : Icons.play_circle,
            color: Colors.white,
          ),
          iconSize: 60,
          onPressed: () {
            setState(() {
              isPlaying = !isPlaying;

              if (isPlaying) {
                _coverCtrl.repeat();
              } else {
                _coverCtrl.stop();
              }
            });
          },
        ),
        IconButton(
          icon: const Icon(Icons.skip_next, color: Colors.white),
          iconSize: 40,
          onPressed: () {
            // TODO: 下一曲
          },
        ),
      ],
    );
  }

// 如果后面需要重新启用底部主题选择，可以解开这里的注释
// Widget _buildThemeSelector() { ... }
}

/// 高质感旋钮 Painter：
/// - 外圈刻度（左亮右暗，随音量变化）
/// - 中间暗灰渐变圆盘
/// - 顶部播放指示灯（播放时亮）
/// - 中心轻微呼吸光（用 glow 控制）
class _KnobPainter extends CustomPainter {
  final double volume;   // 0~1
  final double glow;     // 0~1
  final bool isPlaying;

  _KnobPainter({
    required this.volume,
    required this.glow,
    required this.isPlaying,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final center = size.center(Offset.zero);
    final radius = size.width / 2;

    // 1. 背景圆盘（径向渐变）
    final bgPaint = Paint()
      ..shader = const RadialGradient(
        colors: [
          Color(0xFF2A2A2A),
          Color(0xFF050505),
        ],
      ).createShader(Rect.fromCircle(center: center, radius: radius));
    canvas.drawCircle(center, radius, bgPaint);

    // 2. 外圈描边
    final borderPaint = Paint()
      ..style = PaintingStyle.stroke
      ..strokeWidth = 3
      ..color = Colors.white10;
    canvas.drawCircle(center, radius - 2, borderPaint);

    // 3. 刻度（对称 + 只点亮一段）
    final tickActivePaint = Paint()
      ..strokeWidth = 3
      ..strokeCap = StrokeCap.round
      ..color = Colors.cyanAccent;

    final tickInactivePaint = Paint()
      ..strokeWidth = 2
      ..strokeCap = StrokeCap.round
      ..color = Colors.grey.shade700;

    const int tickCount = 40;
    const double startDeg = -130;
    const double endDeg = 130;

    final sweep = endDeg - startDeg;
    final activeDeg = startDeg + sweep * volume; // 当前音量对应的角度

    for (int i = 0; i < tickCount; i++) {
      final t = i / (tickCount - 1);
      final angDeg = lerpDouble(startDeg, endDeg, t)!;
      final angRad = angDeg * pi / 180;

      final x1 = center.dx + (radius - 14) * cos(angRad);
      final y1 = center.dy + (radius - 14) * sin(angRad);
      final x2 = center.dx + (radius - 6) * cos(angRad);
      final y2 = center.dy + (radius - 6) * sin(angRad);

      final isActive = angDeg <= activeDeg;
      canvas.drawLine(
        Offset(x1, y1),
        Offset(x2, y2),
        isActive ? tickActivePaint : tickInactivePaint,
      );
    }

    // 4. 中心小圆 + 呼吸光
    final innerR = radius * 0.45;
    final innerPaint = Paint()
      ..shader = RadialGradient(
        colors: [
          Colors.white.withOpacity(0.12 + 0.10 * glow),
          Colors.black,
        ],
      ).createShader(Rect.fromCircle(center: center, radius: innerR));
    canvas.drawCircle(center, innerR, innerPaint);

    // 5. 播放状态指示灯（顶部小灯）
    final ledPaint = Paint()
      ..color = isPlaying
          ? Colors.greenAccent.withOpacity(0.9)
          : Colors.grey.shade600;

    final ledOffset = Offset(
      center.dx,
      center.dy - innerR + 10,
    );
    canvas.drawCircle(ledOffset, 5, ledPaint);
  }

  @override
  bool shouldRepaint(covariant _KnobPainter oldDelegate) {
    return oldDelegate.volume != volume ||
        oldDelegate.glow != glow ||
        oldDelegate.isPlaying != isPlaying;
  }
}

// --------------------------------------------
// 主题配置（图片路径按你的实际 assets 调整）
// --------------------------------------------
class MusicTheme {
  final String title;
  final String image;
  final String desc;

  const MusicTheme({
    required this.title,
    required this.image,
    required this.desc,
  });
}

const List<MusicTheme> musicThemes = [
  MusicTheme(
    title: "临隙晨光",
    image: "assets/music/morning.png",
    desc: "林深时见光，唤醒沉睡梦。",
  ),
  MusicTheme(
    title: "月夜独思",
    image: "assets/music/moon.png",
    desc: "月色漫山岗，人影立苍茫。",
  ),
  MusicTheme(
    title: "灵感自习",
    image: "assets/music/study.png",
    desc: "案头小天地，思绪会开花。",
  ),
  MusicTheme(
    title: "城市夜曲",
    image: "assets/music/city.png",
    desc: "灯火映长河，城市披星河。",
  ),
];
